<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name" :rules="[{ required: true, message: '分类名称为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="分类名称" tooltip="通知分类的名称" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Code_FormItem" prop="Entity.Code">
								<template #label>
									<WtmLabelTooltip label="分类编码" tooltip="通知分类的唯一编码" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Code" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Description_FormItem" prop="Entity.Description">
								<template #label>
									<WtmLabelTooltip label="分类描述" tooltip="通知分类的详细描述" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Description" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Icon_FormItem" prop="Entity.Icon">
								<template #label>
									<WtmLabelTooltip label="分类图标" tooltip="通知分类的图标" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Icon" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>发送配置</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EnableInternalMessage_FormItem"
								prop="Entity.EnableInternalMessage"
								:rules="[{ required: true, message: '启用站内信为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="启用站内信" tooltip="是否启用站内信通知" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.EnableInternalMessage" clearable class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EnableSms_FormItem"
								prop="Entity.EnableSms"
								:rules="[{ required: true, message: '启用短信为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="启用短信" tooltip="是否启用短信通知" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.EnableSms" clearable class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EnableEmail_FormItem"
								prop="Entity.EnableEmail"
								:rules="[{ required: true, message: '启用邮件为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="启用邮件" tooltip="是否启用邮件通知" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.EnableEmail" clearable class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EnableAppPush_FormItem"
								prop="Entity.EnableAppPush"
								:rules="[{ required: true, message: '启用APP推送为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="启用APP推送" tooltip="是否启用APP推送通知" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.EnableAppPush" clearable class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EnableWechatPush_FormItem"
								prop="Entity.EnableWechatPush"
								:rules="[{ required: true, message: '启用微信推送为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="启用微信推送" tooltip="是否启用微信推送通知" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.EnableWechatPush" clearable class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EnableDingTalkPush_FormItem"
								prop="Entity.EnableDingTalkPush"
								:rules="[{ required: true, message: '启用钉钉推送为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="启用钉钉推送" tooltip="是否启用钉钉推送通知" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.EnableDingTalkPush" clearable class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_DefaultPriority_FormItem"
								prop="Entity.DefaultPriority"
								:rules="[{ required: true, message: '默认优先级为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="默认优先级" tooltip="该分类通知的默认优先级" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.DefaultPriority" clearable class="width100">
									<el-option key="低" value="低" label="低"></el-option>
									<el-option key="普通" value="普通" label="普通"></el-option>
									<el-option key="高" value="高" label="高"></el-option>
									<el-option key="紧急" value="紧急" label="紧急"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>状态信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_IsEnabled_FormItem"
								prop="Entity.IsEnabled"
								:rules="[{ required: true, message: '是否启用为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="是否启用" tooltip="是否启用该通知分类" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.IsEnabled" clearable class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_SortOrder_FormItem"
								prop="Entity.SortOrder"
								:rules="[{ required: true, message: '排序号为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="排序号" tooltip="分类的显示排序" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.SortOrder" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<el-row :gutter="20">
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_ParentId_FormItem" prop="Entity.ParentId" label="父级">
							<el-select v-model="stateData.vmModel.Entity.ParentId" clearable class="width100">
								<el-option v-for="item in stateData.AllSysNotificationCategorys" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysNotificationCategoryApi as api } from '/@/views/_admin/sysnotificationcategory/api';
import other from '/@/utils/other';
import { ISysNotificationCategoryVm } from '/@/views/_admin/sysnotificationcategory/api/interface';
import { IViewModel } from '/@/types/common';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);
const stateData = reactive<IViewModel<ISysNotificationCategoryVm>>({
	vmModel: {
		Entity: {
			Name: null,
			Code: null,
			Description: null,
			Icon: null,
			EnableInternalMessage: false,
			EnableSms: false,
			EnableEmail: false,
			EnableAppPush: false,
			EnableWechatPush: false,
			EnableDingTalkPush: false,
			DefaultPriority: '低',
			IsEnabled: false,
			SortOrder: 0,
			ParentId: null,
		},
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysNotificationCategorys: [],
});

const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});
const handleApiResponse = (response: any) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response))
				.catch(handleError);
		}
	});
};
// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {},
		false
	);
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other
			.getSelectList('/api/SysNotificationCategory/GetSysNotificationCategorys', [], false)
			.then((x) => (stateData.AllSysNotificationCategorys = x)),
	]);
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
